using OpenViewer.Render;
using ThirdLife.UI.WinForms.Controls;

namespace ThirdLife.UI.WinForms.Modules
{
  public class Canvas3D : IUIModule
  {
    private TLCanvas3D _3darea;
    private IUIModuleServices _moduleServices;
    IRenderingEngine renderingEngine;

    #region IUIModule Members

    public IUIModuleServices ModuleServices
    {
      get { return _moduleServices; }
      set { _moduleServices = value; }
    }

    public string Name
    {
      get { return "ThirdLife_MetaverseDisplay"; }
    }

    public void Setup()
    {
      _3darea = new TLCanvas3D(this);
      
      ModuleServices.Startup.ApplicationStarted += Startup_ApplicationStarted;
      ModuleServices.Metaverse.ReadyForRendering += new GenericEventHandler(OnReadyForRendering);
      UIModuleServices.Instance.Metaverse.DisconnectFromGrid += new GenericEventHandler(Metaverse_DisconnectFromGrid);
    }

    private void Metaverse_DisconnectFromGrid()
    {
      _3darea.ShowNonRenderingScreen();

      
    }

    private void OnReadyForRendering()
    {
      _3darea.ClearAllControls();

      
      renderingEngine = ModuleServices.Metaverse.RenderingEngineGenerator.Generate(_3darea.ShowReneringAreaAndGetDrawingAreaHandle());
      renderingEngine.Run();
    }

    #endregion

    private void Startup_ApplicationStarted()
    {
      ModuleServices.Registration.AddToMainScreen(_3darea, new DockLocation(_3darea.Height, 2, false));
    }

    public void TryToSafelyStopRenderer()
    {
      renderingEngine.Stop();
    }
  }
}